package com.simafei.flow.core.rule.action;

import cn.hutool.core.collection.CollectionUtil;
import com.simafei.flow.core.FlowConstants;
import com.simafei.flow.core.rule.Action;
import com.simafei.flow.core.rule.FlowRule;
import com.simafei.flow.core.rule.ValueHandler;
import lombok.RequiredArgsConstructor;
import org.jeasy.rules.api.Facts;

import java.util.Map;

/**
 * 赋值行为
 * @author fengpengju
 */
@RequiredArgsConstructor
public class AssignAction implements Action {

    private final FlowRule flowRule;

    @Override
    public void eval(Facts facts) {
        Map<String, Object> results = facts.get(FlowConstants.RULE_RESULTS);

        results.put(FlowConstants.RULE_NAME_COLUMN, flowRule.getRuleName());

        if (CollectionUtil.isNotEmpty(flowRule.getAssignments())) {
            flowRule.getAssignments().forEach(assignment -> {
                Object result = ValueHandler.handle(assignment.getRight(), assignment.getRightFieldType(), assignment.getRightType(), facts.asMap());
                results.put(assignment.getLeft(), result);
            });
        }
    }
}
